package com.xinyue.auto.reader.util;

import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.xinyue.auto.Label;
import com.xinyue.auto.util.StringUtil;

public class OrderUtil implements Label{
	
	/**
	 * 验证比较器是否合法
	 * @param cpt
	 * @param orderBy
	 * @return
	 * @throws Exception
	 */
	public static String validate(List<Element> os, Element xml) throws Exception {
		String orderBy = "";
		
		for (Element o: os) {
			String by = o.attributeValue(by_);
			String name = o.attributeValue(name_);
			
			//验证name属性是否合法
			if(StringUtil.isNull(name)) {
				throw new Exception("order-column标签name属性未定义或其值为空");
			}
			//验证name是否是entity下的属性
			Node n = xml.selectSingleNode("id[@name='" + name + "']");
			if(n == null) {
				n = xml.selectSingleNode("property[@name='" + name + "']");
			}
			if(n == null) {
				throw new Exception("order-column标签name属性值非法:" + name);
			}
			
			//验证order并合成Hql语句
			if(StringUtil.isNull(by)) {
				by = "ASC";
			}else if(!"DESC".equals(by) && !"ASC".equals(by)){
				throw new Exception("order-column标签by属性值非法:" + by);
			}
			
			//合并order子句
			orderBy += name + " " + by + ", ";
		}
		
		orderBy = " order by " + orderBy.substring(0, orderBy.length() - 2);
		
		return orderBy;
	}
}
